import React, { Dispatch, ReactNode, SetStateAction, useEffect, useRef, useState } from 'react';
import {
	screenshot,
	screenShare,
	sendVideoLink,
	sendCustomizeMessage,
	sendViewResource,
	sendScannerCode,
	cancelScannerCode,
	requestGeolocation,
	sendLink,
	screenCapture,
	startRecordScreen,
	cardRecognition,
	faceRecognition,
	endScreenShare,
	stopRecordScreen,
	cancelRequestCustomerLocation,
	cancelHandWriting,
	requestHandSign,
	sendPDF,
	requestFillForm,
	cancelRequestFillForm,
	saveScreenShareRecord,
	saveStopScreenShareRecord,
	requestCollectIdCard,
	cancelIdCardCollection,
	requestCollectBankCard,
	cancelBankCardCollection,
	sendWhiteBoard,
	startWhiteboard,
	deleteWhiteboard,
	cancelWhiteBoard,
	sendPdfWhiteboard,
	cancelPdfWhiteboard,
	sendTestimonyWrite,
	cancelTestimonyWrite,
	sendCollectVariable,
	cancelCollectVariable,
	startPdfWhiteboard,
	deletePdfWhiteboard,
	startTestimonyWrite,
	deleteTestimonyWrite,
	collectShortVideo,
	cancelCollectShortVideo,
	startRecordRegionalScreen,
	stopRecordRegionalScreen,
	sendKnowledgeBase,
	customerViewMark,
	cancelCustomerViewMark
} from './utils/requestBusiness';
import {
	onScreenShot,
	onFillForm,
	onGeoLocation,
	onHandWriting,
	onScanCode,
	receiveCustomizeMessageData,
	onViewResource,
	onScreenCapture,
	onIdCardCollectResult,
	onBankCardCollectResult,
	onTestimonyWriteResult,
	onCollectVariableResult,
	onPdfWhiteboardResult,
	onWhiteboardResult,
	onCollectShortVideoResult,
	onCustomerViewMarkResult
} from './utils/responseBusiness';
import BusinessQueneTask from './utils/BusinessQueneTask';
import Message from '@/utils/message';
import AgentService from '@/modules/Agent';
import { useSelector } from 'react-redux';

import useSyncState from '../hooks/useSyncState';
import store from '@/store';
import { getFormFollowId, updateFormRecord } from '@/api';
import { useTranslation } from 'react-i18next';
import i18next from '../../utils/i18next/i18n';
import { appendToken } from '@/utils';
// import { createCustomerStreamContainer } from '../CustomerStreamMark';

export interface ICustomerMembers extends IMembersProps {}

export interface IAgentMembers extends IMembersProps {}

export interface IStream {
	id: string | undefined;
	label: string;
	audioOnly: boolean;
	clientId: string;
	videoId: string;
	muteStatus: boolean;
	streamMode: 'audio' | 'video';
	role: string;
	isScreenSyncMode: boolean;
	userName: string;
}

/** 指令枚举 */
export enum IBusinessName {
	SCREEN_SHOT = 'screenshot',
	SCREEN_SHARE = 'screenShare',
	SEND_LINK = 'sendLink',
	SEND_VIDEO_LINK = 'sendVideoLink',
	SEND_SCANNER_CODE = 'sendScannerCode',
	CANCEL_SCANNER_CODE = 'cancelScannerCode',
	REQUEST_GEO_LOCATION = 'requestGeoLocation',
	FACE_COMPARE = 'faceCompare',
	SNAP_SHOT = 'snapShot',
	RECORD_SCREEN = 'recordScreen',
	CARD_COMPARE = 'cardCompare',
	SCREEN_MARK = 'screenMark',
	GET_GEO_LOCATION = 'getGeoLocaltion',
	SEND_SIGN = 'sendSign',
	FILL_FORM = 'fillForm',
	SEND_PDF = 'sendPDF',
	SEND_CARD_COLLECTION = 'sendCardCollection',
	SEND_IDCARD_COLLECTION = 'sendIdCardCollection',
	SEND_BANKCARD_COLLECTION = 'sendBankCardCollection',
	SHARED_WHITEDOARD = 'sharedWhiteboard',
	SHARED_PDF = 'sharedPDF',
	SEND_VARIABLE_COLLECTION = 'sendVariableCollection',
	TRANSCRIPT_OF_TESTIMONY = 'transcriptOfTestimony',
	SEND_VIDEO_COLLECTION = 'sendVideoCollection',
	TTS_BROADCAST = 'ttsBroadcast',
	REGIONAL_SCREEN_RECORDING = 'regionalScreenRecording',
	SEND_KNOWLEDGE_BASE = 'sendKnowledgeBase',
	CUSTOMER_VIEW_MARK = 'customerViewMark' // 访客画面实时标注
}

export enum IBusinessStatus {
	IDLE = 'idle',
	START = 'start',
	IN_PROGRESS = 'in-progress',
	REJECTED = 'rejected',
	FAILED = 'failed',
	CANCEL = 'cancel',
	DONE = 'done',
	ACCEPTED = 'accepted'
}

export const ignoreBusiness = [IBusinessName.SEND_LINK, IBusinessName.SEND_VIDEO_LINK, IBusinessName.RECORD_SCREEN, IBusinessName.REGIONAL_SCREEN_RECORDING];

export const ignoreMessage = [IBusinessName.RECORD_SCREEN, IBusinessName.SCREEN_SHARE, IBusinessName.SCREEN_MARK, IBusinessName.REGIONAL_SCREEN_RECORDING];

export const ignoreAudioBusiness = [IBusinessName.CARD_COMPARE, IBusinessName.SEND_SCANNER_CODE, IBusinessName.FACE_COMPARE, IBusinessName.SCREEN_SHOT, IBusinessName.CUSTOMER_VIEW_MARK];

export interface IBusinessProps {
	businessName: IBusinessName;
}

/** 业务指令类 */
export const BusinessTaskMap = new BusinessQueneTask();

export const ReceiveBroadcastMap: Map<string, IReceiveBroadcas> = new Map();

type ISendBusiness = (cmd: IBusinessName, data: any, receivers: string[]) => void;

type IReceiveBroadcas = {
	createdAt: string;
	data: {
		content: {
			fromUserName: string;
			status: IBusinessStatus;
			name: IBusinessName;
			toClientId: string;
			userRole: string;
			username: string;
			type: 'broadcast';
		};
		fromUser: IMembersProps['label'];
		label: IMembersProps['label'];
		type: 'broadcast';
	};

	from: string;
	fromUser: { id: number; name: string; avatar: string; isRobot: boolean };
	id: string;
	to: string;
	type: string;
};

interface IMembersProps {
	id: string;
	clientId: string;
	username: string;
	userRole: string;
	label: 'customer' | 'agent' | null;
}

export interface IBusiness {
	name: IBusinessName;
	status: IBusinessStatus;
	clientId: string;
	username: string;
	userRole: string;
	cmdId: number | null;
}

const selfBusiness = [IBusinessName.RECORD_SCREEN, IBusinessName.REGIONAL_SCREEN_RECORDING];

const initRecordData = {
	publicationId: '',
	recordId: '',
	recordStatus: IBusinessStatus.IDLE,
	clientId: ''
};

interface IRecord {
	publicationId: string;
	recordId: string;
	recordStatus: IBusinessStatus;
	clientId: string;
}

interface IForm {
	clientId: string;
	formId: string | number;
	formTemplate: string | number;
	cmdId?: number;
}

export enum notifyMessage {
	'screenshot' = 'screenshot',
	'screenShare' = 'screenShare',
	'sendLink' = 'sendLink',
	'sendVideoLink' = 'sendVideoLink',
	'sendScannerCode' = 'sendScannerCode',
	'cancelScannerCode' = 'cancelScannerCode',
	'requestGeoLocation' = 'requestGeoLocation',
	'faceCompare' = 'faceCompare',
	'snapShot' = 'snapShot',
	// 'recordScreen' = 'recordScreen',
	'cardCompare' = 'cardCompare',
	'getGeoLocaltion' = 'getGeoLocaltion',
	'sendSign' = 'sendSign',
	'fillForm' = 'fillForm',
	'sendPDF' = 'sendPDF',
	'sendIdCardCollection' = 'sendIdCardCollection',
	'sendBankCardCollection' = 'sendBankCardCollection',
	'sharedWhiteboard' = 'sharedWhiteboard',
	'sharedPDF' = 'sharedPDF',
	'transcriptOfTestimony' = 'transcriptOfTestimony',
	'sendVariableCollection' = 'sendVariableCollection',
	'sendVideoCollection' = 'sendVideoCollection',
	'customerViewMark' = 'customerViewMark'
}

type CustomerLabel = 'username' | 'userRole';

type MembersLabel = 'customer' | 'agent' | null;

/** 警告提示 */
const warning = (username: string) => {
	const client = i18next.t('current-client');
	Message.warning(`${client} ${username} ` + i18next.t('ongoing-business-finish-operation'));
};

const BusinessContext = React.createContext<
	| {
			customerMembers: () => IMembersProps[];
			agentMembers: () => IMembersProps[];
			membersJoin: (member: IMembersProps) => void;
			membersLeave: (clientId: string) => void;
			getMembersLabel: (label: string) => MembersLabel | null;
			getCustomerMembers: (label: CustomerLabel | null) => IStream[];
			sendBusiness: ISendBusiness;
			setAgentName: Dispatch<SetStateAction<string>>;
			setBusiness: Dispatch<SetStateAction<IBusiness[]>>;
			BusinessTaskMap: BusinessQueneTask;
			business: IBusiness[];
			record: () => IRecord;
			screenId: () => string;
			setScreenId: (screenId: string) => void;
			setRecord: (data: IRecord) => void;
			setAllMembers: (data: IMembersProps[]) => void;
			setCustomerMembers: (data: IMembersProps[]) => void;
			cancelBusiness: (clientId: string, name: IBusinessName) => void;
			notifyOtherAgents: (task: IBusinessName, status: IBusinessStatus, client: IStream) => void;
			setBizScenarioId: (id: string | number) => void;
			bizScenarioId: () => string | number;
			formBusiness: () => IForm[];
			agentLeaveSession: (clientId: string) => void;
			whiteBoardBtnStatus: () => string;
			setWhiteBoardBtnStatus: (whiteBoardBtnStatus: string) => void;
			sharePdfBtnStatus: () => string;
			setSharePdfBtnStatus: (sharePdfBtnStatus: string) => void;
			startWhiteBoard: () => void;
			startPdfWhiteBoard: (url: string) => void;
			recordRegion: () => IRecord;
			setRecordRegion: (data: IRecord) => void;
	  }
	| undefined
>(undefined);
BusinessContext.displayName = 'BusinessContext';

const BusinessProvider = ({ children }: { children: ReactNode }) => {
	const { t } = useTranslation();
	const [customerMembers, setCustomerMembers] = useSyncState<ICustomerMembers[]>([]);
	const [agentMembers, setAgentMembers] = useSyncState<IAgentMembers[]>([]);
	const [allMembers, setAllMembers] = useSyncState<IMembersProps[]>([]);
	const [business, setBusiness] = useState<IBusiness[]>([]);
	const [agentName, setAgentName] = useState<string>('');
	const [record, setRecord] = useSyncState<IRecord>(initRecordData);
	const [bizScenarioId, setBizScenarioId] = useSyncState<string | number>('');
	const [screenId, setScreenId] = useSyncState<string>('');
	const [formBusiness, setFormBusiness] = useSyncState<{ clientId: string; data: IForm[] }[]>([]);
	const [recordRegion, setRecordRegion] = useSyncState<IRecord>(initRecordData); // 区域录屏

	//共享白板按钮状态
	const [whiteBoardBtnStatus, setWhiteBoardBtnStatus] = useSyncState<string>('default'); //default 默认状态 open 展开状态 stow 收起状态
	//共享PDF按钮状态
	const [sharePdfBtnStatus, setSharePdfBtnStatus] = useSyncState<string>('default'); //default 默认状态 open 展开状态 stow 收起状态

	const eventRef = useRef<boolean>(false);

	useEffect(() => {
		eventRef.current = false;
	}, [AgentService.getAgentMediaStreams().length === 0]);

	useEffect(() => {
		if (AgentService.getCustomerMediaStream().length === 0) {
			setScreenId('');
			eventRef.current = false;
		}
	}, [AgentService.getCustomerMediaStream()]);

	/** 用户加入会话 */
	const membersJoin = (member: IMembersProps) => {
		setAllMembers([...allMembers(), member]);
	};

	/** 用户离开当前会话 */
	const membersLeave = (clientId: string) => {
		setAllMembers(allMembers().filter(item => item.clientId !== clientId));
		/** 访客离开检查任务队列 */
		if (BusinessTaskMap.hasTask(clientId)) {
			BusinessTaskMap.delTask(clientId)
				.then(resp => {
					console.log(resp);
				})
				.catch(e => {
					console.log(e);
				});
		}
	};

	/** 获取访客用户列表 */
	const getCustomerMembers = (label: CustomerLabel | null) => {
		// let members: IMembersProps[] = [];
		// if (!label) return customerMembers();
		// members = customerMembers().filter(item => item[label]);
		return AgentService.getAllMediaSteams().filter(item => item.label.indexOf('customer') > -1);
	};

	/** 筛选出指令接收者， 发送业务指令 */
	const sendBusiness: ISendBusiness = (cmd, data, receivers) => {
		const members = getGoodNetWork(receivers);
		console.warn('sendBusiness : ', cmd, data, receivers, AgentService.getCustomerMediaStream(), members);
		return new Promise((resolve, reject) => {
			let isSendMessage = false;
			if (!Array.isArray(members)) {
				return Promise.reject({ code: 400, message: `${members} is not array` });
			} else if (cmd === IBusinessName.SCREEN_SHARE) {
				agentScreenShare(cmd, data, members);
			} else {
				let num = 0;
				for (let key of validateClientMembers(members, cmd)) {
					/** 是否正在进行指令中 */
					if ((BusinessTaskMap.hasTask(key) || customerHasInProgressTask(key)) && selfBusiness.indexOf(cmd) === -1) {
						const resp: IBusiness | null = BusinessTaskMap.getTask(key);
						const task = customerHasInProgressTask(key);
						if (resp) warning(resp.username);
						if (task) warning(task.data.content.username);
						console.log('validateClientMembers:', resp);
					} else {
						const receiver = AgentService.getCustomerMediaStream().find(item => item.clientId === key);
						console.log('send bussiness receiver', receiver);
						/** 是否仅对自己生效 */
						if (selfBusiness.indexOf(cmd) > -1) {
							resolve(AgentService.currentAgentStream && sendBusinessMessage(cmd, data, AgentService.currentAgentStream));
						} else {
							resolve(receiver && sendBusinessMessage(cmd, data, receiver));
						}
						if (ignoreMessage.indexOf(cmd) <= -1) {
							console.log(ignoreMessage.indexOf(cmd));
							notifyMessage[cmd] && !isSendMessage && Message.normal(t('notifyMessage' + '.' + notifyMessage[cmd]));
							isSendMessage = true;
						}
					}
					num++;
					delectWhiteBoardWhitId(cmd, members, num);
				}
			}
		});
	};

	useEffect(() => {
		if (!AgentService.whiteboardId) {
			setWhiteBoardBtnStatus('default');
		}
		if (!AgentService.pdfWhiteBoardId) {
			setSharePdfBtnStatus('default');
		}
	}, [AgentService.whiteboardId, AgentService.pdfWhiteBoardId]);

	const delectWhiteBoardWhitId = async (type: any, receivers: any, index: number) => {
		if (validateWhiteBoardClientMembers(receivers, type).length !== index) return;
		if (type === IBusinessName.SHARED_WHITEDOARD) {
			if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SHARED_WHITEDOARD).length === 0 && AgentService.whiteboardId) {
				const result = await deleteWhiteboard(AgentService.whiteboardId);
				setWhiteBoardBtnStatus('default');
				AgentService.whiteboardId = '';
			}
		} else if (type === IBusinessName.SHARED_PDF) {
			if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SHARED_PDF).length === 0 && AgentService.pdfWhiteBoardId) {
				const result = await deletePdfWhiteboard(AgentService.pdfWhiteBoardId);
				setSharePdfBtnStatus('default');
				AgentService.pdfWhiteBoardId = '';
			}
		}
	};

	/** 其他坐席是否对访客有未完成的业务 */
	const customerHasInProgressTask = (clientId: string) => {
		const task = ReceiveBroadcastMap.get(clientId);
		console.log('customerHasInProgressTask:', task, ReceiveBroadcastMap, clientId);
		if (task?.data.content.status === IBusinessStatus.IN_PROGRESS) {
			return task;
		}
		// 访客接受实时标注
		if (task?.data.content.name === 'customerViewMark' && task?.data.content.status === IBusinessStatus.ACCEPTED) {
			return task;
		}
	};

	/** 坐席离开清除访客任务 */
	const agentLeaveSession = (clientId: string) => {
		for (let [key, val] of ReceiveBroadcastMap) {
			if (val.from === clientId) {
				ReceiveBroadcastMap.has(key) && ReceiveBroadcastMap.delete(key);
			}
		}

		console.log('ReceiveBroadcastMap:', ReceiveBroadcastMap);
	};

	/** 屏幕共享 */
	const agentScreenShare: ISendBusiness = (cmd, data, receivers) => {
		let isCreated = false;
		if (screenId() !== '') {
			insertScreenShareToTask(receivers, cmd, screenId());
		} else {
			receivers.map(client => {
				if (!customerHasInProgressTask(client) && !isCreated && !BusinessTaskMap.hasTask(client)) {
					screenShare()
						.then(success => {
							setScreenId(success as string);
							insertScreenShareToTask(receivers, cmd, screenId());
							Message.normal(t('start-screen-sharing'));
						})
						.catch(e => {
							console.log(e);
						});
					isCreated = true;
				} else {
					const task = customerHasInProgressTask(client);
					const progressTask: IBusiness | null = BusinessTaskMap.getTask(client);
					if (task) warning(task.data.content.username);
					if (progressTask) warning(progressTask.username);
				}
			});
		}
		console.log('agentScreenShare:', AgentService.currentAgentStream);
	};

	/** 插入屏幕共享操作到任务队列 */
	const insertScreenShareToTask = (receivers: string[], cmd: IBusinessName, cmdId: string) => {
		receivers.map(async client => {
			if (BusinessTaskMap.hasTask(client) || customerHasInProgressTask(client)) {
				const resp: IBusiness | null = BusinessTaskMap.getTask(client);
				if (resp) warning(resp.username);
				const task = customerHasInProgressTask(client);
				if (task) warning(task.data.content.username);
				console.log('insertScreenShareToTask:', resp);
			} else {
				const agent = AgentService.currentAgentStream;
				const receiver = AgentService.getCustomerMediaStream().find(item => item.clientId === client);
				if (agent && receiver) {
					BusinessTaskMap.addTask(receiver.clientId, {
						name: cmd,
						clientId: receiver.clientId,
						status: IBusinessStatus.START,
						username: receiver.userName,
						userRole: receiver.role,
						cmdId: Number(cmdId)
					});
					setBusiness([
						...business,
						{
							name: cmd,
							clientId: receiver.clientId,
							status: IBusinessStatus.START,
							username: receiver.userName,
							userRole: receiver.role,
							cmdId: Number(cmdId)
						}
					]);
					notifyCustomers(receiver, `${AgentService.user?.userName}-screen`, 'start-screen-share');
					saveScreenShareRecord(receiver.clientId);
					notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, receiver);
					await BusinessTaskMap.updateTaskStatus(receiver.clientId, IBusinessStatus.IN_PROGRESS, Number(cmdId));
				}
			}
		});
	};

	/** 停止屏幕共享 */
	const stopScreenShare = async (clientId: string) => {
		const receiver = AgentService.getCustomerMediaStream().find(item => item.clientId === clientId);
		// Message.normal(`结束访客<${receiver?.username}>的屏幕共享`);
		if (receiver) {
			notifyCustomers(receiver, `${AgentService.user?.userName}-screen`, 'stop-screen-share');
			saveStopScreenShareRecord(receiver.clientId);
			const cmdId = screenId() ? Number(screenId()) : -1;
			await BusinessTaskMap.updateTaskStatus(clientId, IBusinessStatus.DONE, cmdId);
			setBusiness([
				...business,
				{
					name: IBusinessName.SCREEN_SHARE,
					clientId: receiver.clientId,
					status: IBusinessStatus.IDLE,
					username: receiver.userName,
					userRole: receiver.role,
					cmdId: null
				}
			]);
		}
		if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SCREEN_SHARE).length === 1) {
			console.log('findTaskWithTaskName:', screenId());

			await endScreenShare(screenId(), false);
			setScreenId('');
		}
		receiver && notifyOtherAgents(IBusinessName.SCREEN_SHARE, IBusinessStatus.DONE, receiver);
		const task = await BusinessTaskMap.getTask(clientId);
		task && BusinessTaskMap.addCompletedTask({ task: IBusinessName.SCREEN_SHARE, data: task, response: null, isRead: false });
	};

	/** 通知其他坐席, 当前访客正在进行中的指令 IStream | IBusiness */
	const notifyOtherAgents = (task: IBusinessName, status: IBusinessStatus, client: any) => {
		agentMembers().map(item => {
			let data = {
				type: 'broadcast',
				fromUser: item.username,
				label: item.label,
				content: {
					name: task,
					fromUserName: item.username,
					userRole: client.role ? client.role : client.userRole,
					username: client.userName ? client.userName : client.username,
					toClientId: client.clientId,
					status: status,
					type: 'broadcast'
				}
			};
			if (item.clientId !== AgentService.user?.clientId) {
				sendCustomizeMessage(data, item.clientId);
			}
		});
	};

	/** 通知访客, 当前访客正在进行中的指令 */
	const notifyCustomers = async (receiver: IStream, screenLabel: string, businessType: string) => {
		let data = {
			businessType: businessType,
			screenLabel: screenLabel,
			fromUser: AgentService.user?.userName,
			label: 'agent',
			content: {
				task: IBusinessName.SCREEN_SHARE,
				fromUserName: AgentService.user?.userName,
				toRole: receiver.role,
				toUserName: receiver.userName,
				toClientId: receiver.clientId,
				status: businessType
			}
		};
		console.log('notifyCustomers:', data);
		sendCustomizeMessage(data, receiver.clientId);
	};

	/** 从 memerbs 中获取，用户标签 */
	const getMembersLabel = (label: string): MembersLabel | null => {
		if (label.indexOf('customer') > -1) {
			return 'customer';
		} else if (label.indexOf('agent') > -1) {
			return 'agent';
		} else {
			return null;
		}
	};

	/** 用户点击停止分享，终止录制 */
	const systemStopRecord = () => {
		setRecord({ clientId: '', publicationId: '', recordId: '', recordStatus: IBusinessStatus.DONE });
	};

	/** 用户点击停止区域录制 */
	const systemStopRecordRegion = () => {
		setRecordRegion({ clientId: '', publicationId: '', recordId: '', recordStatus: IBusinessStatus.DONE });
	};

	/** 访客是否在音频呼叫 */
	const validateClientMembers = (members: string[], cmd: IBusinessName) => {
		console.log('validateClientMembers', members);
		const validatedClients: string[] = [];
		const invalidateClients: string[] = [];
		members.map(client => {
			const stream = AgentService.getAllMediaSteams().find(item => item.clientId === client);
			if (stream) {
				if (stream.streamMode === 'video') {
					validatedClients.push(client);
				} else {
					console.log(ignoreAudioBusiness.indexOf(cmd), cmd);

					if (ignoreAudioBusiness.indexOf(cmd) > -1) {
						if (invalidateClients.indexOf(stream?.userName) === -1) {
							invalidateClients.push(`<${stream?.userName}>`);
						}
					} else {
						validatedClients.push(client);
					}
				}
			}
		});
		invalidBusinessCleint(invalidateClients, cmd);
		return validatedClients;
	};

	const validateWhiteBoardClientMembers = (members: string[], cmd: IBusinessName) => {
		console.log('validateWhiteBoardClientMembers', members);
		const validatedClients: string[] = [];
		const invalidateClients: string[] = [];
		members.map(client => {
			const stream = AgentService.getAllMediaSteams().find(item => item.clientId === client);
			if (stream) {
				if (stream.streamMode === 'video') {
					validatedClients.push(client);
				} else {
					console.log(ignoreAudioBusiness.indexOf(cmd), cmd);

					if (ignoreAudioBusiness.indexOf(cmd) > -1) {
						if (invalidateClients.indexOf(stream?.userName) === -1) {
							invalidateClients.push(`<${stream?.userName}>`);
						}
					} else {
						validatedClients.push(client);
					}
				}
			}
		});
		return validatedClients;
	};

	const getGoodNetWork = (members: string[]) => {
		if (store.getState().networkStatus.remoteStatus.length === 0) return members;
		const goodNetWorkData: string[] = [];
		const poorNetWorkData: string[] = [];
		members.forEach(item => {
			const stream = AgentService.getAllMediaSteams().find(e => e.clientId === item);
			const goodItem: any = store.getState().networkStatus.remoteStatus.find((ele: any) => ele.id === item);
			if (goodItem && goodItem.status === 'connected') {
				goodNetWorkData.push(item);
			} else if (goodItem && goodItem.status !== 'connected') {
				poorNetWorkData.push(`<${stream?.userName}>`);
			} else {
				goodNetWorkData.push(item);
			}
		});
		if (poorNetWorkData.length !== 0) {
			netWorkStatusMessage(poorNetWorkData);
		}
		return goodNetWorkData;
	};

	//访客网络状态不好弹窗提示
	const netWorkStatusMessage = (poorNetWorkData: string[]) => {
		if (poorNetWorkData.length === 0) return;
		const client = t('client');
		poorNetWorkData.forEach(item => {
			Message.warning(`${client}${item}${t('session-broken')}，${t('initiation-failed')}`);
		});
	};

	/** 访客音频呼叫不可执行指令提示 */
	const invalidBusinessCleint = (invalidateClients: string[], cmd: IBusinessName) => {
		console.warn('invalidBusinessCleint:', invalidateClients);

		if (invalidateClients.length === 0) return;
		let message = '';
		const getBusinessName = (cmd: IBusinessName): string => {
			let str = '';
			switch (cmd) {
				case IBusinessName.CARD_COMPARE:
					str = t('face-id-photo-comparison-failed');
					break;
				case IBusinessName.SNAP_SHOT:
					str = t('screenshot-failed');
					break;
				case IBusinessName.SEND_SCANNER_CODE:
					str = t('scan-code-failed');
					break;
				case IBusinessName.SCREEN_SHOT:
					str = t('take-screenshot-failed');
					break;
				case IBusinessName.FACE_COMPARE:
					str = t('face-comparison-failed');
					break;
				case IBusinessName.CUSTOMER_VIEW_MARK:
					str = t('customer-view-mark-failed');
					break;
				default:
					break;
			}
			return str;
		};
		const client = t('client');
		if (invalidateClients.length > 2) {
			message = `${client}${invalidateClients[0] + ',' + invalidateClients[1] + '...'}${getBusinessName(cmd)},` + t('remind-client-upgrade-video-call');
		} else {
			message = `${client}${invalidateClients.join(',')}${getBusinessName(cmd)},` + t('remind-client-upgrade-video-call');
		}

		if (message) {
			Message.warning(message);
		}
	};

	// 创建表单流水号
	const createFormNo = async (clientId: string, templateIds: number[]) => {
		let data = {
			org: AgentService.user?.org || '',
			fromClientId: AgentService.user?.clientId || '',
			toClientId: clientId,
			templateIds,
			sessionId: store.getState().session.sessionId
		};
		return await getFormFollowId(data);
	};

	/** 分发业务指令 */
	const sendBusinessMessage = async (cmd: IBusinessName, data: any, client: IStream) => {
		/** 记录指令信息 */
		if (cmd === IBusinessName.REGIONAL_SCREEN_RECORDING) {
			let key = client.clientId + `-${cmd}`;
			BusinessTaskMap.addTask(key, {
				name: cmd,
				clientId: client.clientId,
				status: IBusinessStatus.START,
				username: client.userName,
				userRole: AgentService.getSessionClientWithLabel(client.videoId)?.customerRole || '',
				cmdId: null
			});
		} else {
			BusinessTaskMap.addTask(client.clientId, {
				name: cmd,
				clientId: client.clientId,
				status: IBusinessStatus.START,
				username: client.userName,
				userRole: AgentService.getSessionClientWithLabel(client.videoId)?.customerRole || '',
				cmdId: null
			});
		}

		console.log('BusinessTaskMap:', BusinessTaskMap);
		setBusiness([
			...business,
			{
				name: cmd,
				clientId: client.clientId,
				status: IBusinessStatus.START,
				username: client.userName,
				userRole: AgentService.getSessionClientWithLabel(client.videoId)?.customerRole || '',
				cmdId: null
			}
		]);
		// if (cmd !== IBusinessName.CUSTOMER_VIEW_MARK) {
		// 	// 访客实时标注 不需要关注访客业务操作
		// 	setBusiness([
		// 		...business,
		// 		{
		// 			name: cmd,
		// 			clientId: client.clientId,
		// 			status: IBusinessStatus.START,
		// 			username: client.userName,
		// 			userRole: AgentService.getSessionClientWithLabel(client.videoId)?.customerRole || '',
		// 			cmdId: null
		// 		}
		// 	]);
		// }

		notifyOtherAgents(cmd, IBusinessStatus.START, client);
		let resp: any = null;
		switch (cmd) {
			case IBusinessName.SCREEN_SHOT:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await screenshot(client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SCREEN_SHARE:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await screenShare();
				console.log('screenShare:', resp);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SEND_VIDEO_LINK:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await sendVideoLink(data, client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SEND_SCANNER_CODE:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await sendScannerCode(client.clientId);
				setBusiness([...business, resp]);
				break;
			// 发送实时标注
			case IBusinessName.CUSTOMER_VIEW_MARK:
				try {
					resp = await customerViewMark(client.clientId, client.id!);
					notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
					// setBusiness([...business, resp]); // 无须关注访客的响应
				} catch (error) {
					console.log('send customerViewMark error:', error);
				}
				break;
			case IBusinessName.CANCEL_SCANNER_CODE:
				// await cancelScannerCode(client.clientId);
				break;
			case IBusinessName.SEND_LINK:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await sendLink(data, client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SNAP_SHOT:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await screenCapture(client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.RECORD_SCREEN:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await startRecordScreen(client.clientId, systemStopRecord);
				setRecord({ ...record(), recordStatus: resp.data.status, recordId: resp.recordId, publicationId: resp.publicationId, clientId: resp.data.clientId });
				setBusiness([...business, resp]);
				//录屏recordingId
				AgentService.setRecordingAlertInformation({ screenRecordingId: resp.recordId ? resp.recordId : 0 });
				break;
			case IBusinessName.CARD_COMPARE:
				resp = await BusinessTaskMap.updateTaskStatus(client.clientId, IBusinessStatus.IN_PROGRESS, null);
				setBusiness([...business, resp]);
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await cardRecognition(client.id!, client.clientId);
				console.log('cardRecognition:', resp);
				resp.imageUrl = AgentService.configure.replaceStaticUrl(resp.imageUrl);
				notifyOtherAgents(cmd, IBusinessStatus.DONE, client);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.FACE_COMPARE:
				resp = await BusinessTaskMap.updateTaskStatus(client.clientId, IBusinessStatus.IN_PROGRESS, null);
				setBusiness([...business, resp]);
				await notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await faceRecognition(client.id!, client.clientId);
				console.log('faceRecognition:', resp);
				resp.imageUrl = AgentService.configure.replaceStaticUrl(resp.imageUrl);
				await notifyOtherAgents(cmd, IBusinessStatus.DONE, client);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.GET_GEO_LOCATION:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await requestGeolocation(client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SEND_SIGN:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await requestHandSign(client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.FILL_FORM:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				const ids = data.map((item: any) => item.formTemplate.id);
				const no = await createFormNo(client.clientId, ids);
				let formDetails = data.map((item: any) => ({
					followId: no.data.data.followId,
					formTemplate: item.formTemplate.id,
					formName: item.formTemplate.name,
					formId: no.data.data.id,
					from: store.getState().agent.userName || '',
					to: client.userName || '',
					title: item.formTemplate.fields.title,
					createdAt: no.data.data.createdAt || new Date()
				}));

				console.log('formDetails:', no, formDetails);

				resp = await requestFillForm(client.clientId, formDetails);
				const form = formBusiness().find(item => item.clientId === client.clientId);
				if (form) {
					setFormBusiness(
						formBusiness().map(item => {
							if (item.clientId === form.clientId) {
								return { clientId: form.clientId, data: formDetails };
							}
							return { clientId: item.clientId, data: formDetails };
						})
					);
				} else {
					setFormBusiness([{ clientId: client.clientId, data: formDetails }, ...formBusiness()]);
				}

				setBusiness([...business, resp]);
				break;
			case IBusinessName.SEND_PDF:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await sendPDF(data, client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SEND_IDCARD_COLLECTION:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await requestCollectIdCard(client.clientId, data?.autoOcr);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SEND_BANKCARD_COLLECTION:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await requestCollectBankCard(client.clientId, data?.autoOcr);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SHARED_WHITEDOARD:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await sendWhiteBoard({ whiteboardId: AgentService.whiteboardId }, client.clientId);
				setBusiness([...business, resp]);
				setWhiteBoardBtnStatus('stow');
				break;
			case IBusinessName.SHARED_PDF:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await sendPdfWhiteboard({ whiteboardId: AgentService.pdfWhiteBoardId, data: data }, client.clientId);
				setBusiness([...business, resp]);
				setSharePdfBtnStatus('stow');
				break;
			case IBusinessName.TRANSCRIPT_OF_TESTIMONY:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await sendTestimonyWrite(data, client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SEND_VARIABLE_COLLECTION:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await sendCollectVariable(data, client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.SEND_VIDEO_COLLECTION:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await collectShortVideo(data, client.clientId);
				setBusiness([...business, resp]);
				break;
			case IBusinessName.REGIONAL_SCREEN_RECORDING:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				const region = document.getElementById('zco-agent-widget-up-down-video-container');
				resp = await startRecordRegionalScreen(client.clientId, region, systemStopRecordRegion);
				setRecordRegion({ ...recordRegion(), recordStatus: resp.data.status, recordId: resp.recordId, publicationId: resp.publicationId, clientId: resp.data.clientId });
				setBusiness([...business, resp]);
				//区域录屏recordingId
				AgentService.setRecordingAlertInformation({ regionalScreenRecordingId: resp.recordId ? resp.recordId : 0 });
				break;
			case IBusinessName.SEND_KNOWLEDGE_BASE:
				notifyOtherAgents(cmd, IBusinessStatus.IN_PROGRESS, client);
				resp = await sendKnowledgeBase(data, client.clientId);
				setBusiness([...business, resp]);
				break;
			default:
				break;
		}
		return resp;
	};

	const startWhiteBoard = async () => {
		const path = `${AgentService.configure.whiteboardInfo.whiteboardPath}/board/index.html`;
		let data: any = null;
		if (!AgentService.whiteboardId) {
			data = await startWhiteboard('whiteboard', path, AgentService.configure.whiteboardInfo.hostName);
			console.log(data, '开启白板成功');
			AgentService.whiteboardId = data.whiteboardId;
			setTimeout(() => {
				document.getElementById('whiteBoard-iframe')?.appendChild(data.iframe);
			}, 200);
		}
	};

	const startPdfWhiteBoard = async (url: string) => {
		const upload = AgentService.configure.serviceUrl + '/ivcs/api/v1/upload';
		const fileUrl = url.replace(/^(http:\/\/)/, 'https://');
		const path = `${AgentService.configure.whiteboardInfo.whiteboardPath}/pdfannotater/index.html?upload=${upload}&token=${AgentService.token}&file=${fileUrl}`;
		let data: any = null;
		if (!AgentService.pdfWhiteBoardId) {
			data = await startPdfWhiteboard('whiteboard', path, AgentService.configure.whiteboardInfo.hostName);
			data.iframe.src = data.iframe.src + `?token=${AgentService.getToken()}`;
			console.log(data, '开启pdf白板成功');
			AgentService.pdfWhiteBoardId = data.whiteboardId;
			setTimeout(() => {
				document.getElementById('pdf-iframe')?.appendChild(data.iframe);
			}, 200);
		}
	};

	const startTestiMonyWrite = async (message: string, clientId: string) => {
		const path = `${AgentService.configure.whiteboardInfo.whiteboardPath}/signaturepad/index.html?tracing=${message}`;

		let data: any = null;
		data = await startTestimonyWrite('TestimonyWrite', path, AgentService.configure.whiteboardInfo.hostName);
		console.log(data, '开启证言抄录白板成功');
		AgentService.TestimonyWriteBoardId = [...AgentService.TestimonyWriteBoardId, { whiteboardId: data.whiteboardId, clientId: clientId }];
		return data.whiteboardId;
	};

	/** 业务指令监听初始化 */
	const onBusinessInit = () => {
		console.log('onBusinessInit:');
		onScreenShot(reveiceBusiness);
		onFillForm(reveiceBusiness);
		onGeoLocation(reveiceBusiness);
		onHandWriting(reveiceBusiness);
		onViewResource(reveiceBusiness);
		onScreenCapture(reveiceBusiness);
		onScanCode(reveiceBusiness);
		receiveCustomizeMessageData(receiveBroadcast);
		onIdCardCollectResult(reveiceBusiness);
		onBankCardCollectResult(reveiceBusiness);
		onTestimonyWriteResult(reveiceBusiness);
		onCollectVariableResult(reveiceBusiness);
		onPdfWhiteboardResult(reveiceBusiness);
		onWhiteboardResult(reveiceBusiness);
		onCollectShortVideoResult(reveiceBusiness);
		onCustomerViewMarkResult(reveiceBusiness);
	};

	/** 取消业务指令 */
	const cancelBusiness = async (clientId: string, businessName: IBusinessName) => {
		switch (businessName) {
			case IBusinessName.SCREEN_SHARE:
				stopScreenShare(clientId);
				break;
			case IBusinessName.RECORD_SCREEN:
				console.log('RECORD_SCREEN:', clientId, record());
				await stopRecordScreen(clientId, record().publicationId, record().recordId);
				setRecord({ clientId: '', publicationId: '', recordId: '', recordStatus: IBusinessStatus.DONE });
				if (AgentService.currentAgentStream?.clientId) {
					await BusinessTaskMap.updateTaskStatus(AgentService.currentAgentStream?.clientId!, IBusinessStatus.DONE, null);
					await BusinessTaskMap.delTask(AgentService.currentAgentStream?.clientId!);
				}
				break;
			case IBusinessName.GET_GEO_LOCATION:
				const task = BusinessTaskMap.getTask(clientId);
				if (task && task.cmdId) {
					const resp = await cancelRequestCustomerLocation(task.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: task.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: task.username,
							userRole: task.userRole,
							cmdId: task.cmdId
						}
					]);
				}
				break;
			case IBusinessName.SEND_SIGN:
				const taskSendSign = BusinessTaskMap.getTask(clientId);
				if (taskSendSign && taskSendSign.cmdId) {
					const resp = await cancelHandWriting(taskSendSign.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: taskSendSign.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: taskSendSign.username,
							userRole: taskSendSign.userRole,
							cmdId: taskSendSign.cmdId
						}
					]);
					const task = await BusinessTaskMap.getTask(clientId);
					if (task) {
						await BusinessTaskMap.addCompletedTask({
							task: IBusinessName.SEND_SIGN,
							data: task,
							response: { data: {}, status: IBusinessStatus.CANCEL },
							isRead: false
						});
					}
				}
				break;
			// 取消实时标注
			case IBusinessName.CUSTOMER_VIEW_MARK:
				const taskCustomerViewMarkSign = BusinessTaskMap.getTask(clientId);
				if (taskCustomerViewMarkSign && taskCustomerViewMarkSign.cmdId) {
					const resp = await cancelCustomerViewMark(taskCustomerViewMarkSign.cmdId.toString(), clientId);
				}
				break;
			case IBusinessName.SEND_SCANNER_CODE:
				const scannerCodetask = BusinessTaskMap.getTask(clientId);
				if (scannerCodetask && scannerCodetask.cmdId) {
					const resp = await cancelScannerCode(scannerCodetask.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: scannerCodetask.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: scannerCodetask.username,
							userRole: scannerCodetask.userRole,
							cmdId: scannerCodetask.cmdId
						}
					]);
				}
				break;
			case IBusinessName.FILL_FORM:
				const fillFormTask = BusinessTaskMap.getTask(clientId);
				console.log('FILL_FORM:', BusinessTaskMap.BusinessQuene, fillFormTask);
				if (fillFormTask && fillFormTask.cmdId) {
					const resp = await cancelRequestFillForm(fillFormTask.cmdId.toString(), clientId);
					console.log('cancelRequestFillForm:', formBusiness());

					setBusiness([
						...business,
						{
							name: fillFormTask.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: fillFormTask.username,
							userRole: fillFormTask.userRole,
							cmdId: fillFormTask.cmdId
						}
					]);
					const task = await BusinessTaskMap.getTask(clientId);

					if (task) {
						await BusinessTaskMap.addCompletedTask({
							task: IBusinessName.FILL_FORM,
							data: task,
							response: { data: formBusiness().find(item => item.clientId === clientId)?.data || [], status: IBusinessStatus.CANCEL },
							isRead: false
						});
					}
				}
				break;
			case IBusinessName.SEND_IDCARD_COLLECTION:
				const cardCollectionTask = BusinessTaskMap.getTask(clientId);
				if (cardCollectionTask && cardCollectionTask.cmdId) {
					const resp = await cancelIdCardCollection(cardCollectionTask.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: cardCollectionTask.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: cardCollectionTask.username,
							userRole: cardCollectionTask.userRole,
							cmdId: cardCollectionTask.cmdId
						}
					]);
					const task = await BusinessTaskMap.getTask(clientId);

					if (task) {
						await BusinessTaskMap.addCompletedTask({
							task: IBusinessName.SEND_IDCARD_COLLECTION,
							data: task,
							response: { data: {}, status: IBusinessStatus.CANCEL },
							isRead: false
						});
					}
				}
				break;
			case IBusinessName.SEND_BANKCARD_COLLECTION:
				const bankcardCollectionTask = BusinessTaskMap.getTask(clientId);
				if (bankcardCollectionTask && bankcardCollectionTask.cmdId) {
					const resp = await cancelBankCardCollection(bankcardCollectionTask.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: bankcardCollectionTask.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: bankcardCollectionTask.username,
							userRole: bankcardCollectionTask.userRole,
							cmdId: bankcardCollectionTask.cmdId
						}
					]);
					const task = await BusinessTaskMap.getTask(clientId);

					if (task) {
						await BusinessTaskMap.addCompletedTask({
							task: IBusinessName.SEND_BANKCARD_COLLECTION,
							data: task,
							response: { data: {}, status: IBusinessStatus.CANCEL },
							isRead: false
						});
					}
				}
				break;
			case IBusinessName.SHARED_WHITEDOARD:
				const shareWhiteBoardTask = BusinessTaskMap.getTask(clientId);
				if (shareWhiteBoardTask && shareWhiteBoardTask.cmdId) {
					const resp = await cancelWhiteBoard(shareWhiteBoardTask.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: shareWhiteBoardTask.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: shareWhiteBoardTask.username,
							userRole: shareWhiteBoardTask.userRole,
							cmdId: shareWhiteBoardTask.cmdId
						}
					]);
					if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SHARED_WHITEDOARD).length === 0) {
						const result = await deleteWhiteboard(AgentService.whiteboardId);
						setWhiteBoardBtnStatus('default');
						AgentService.whiteboardId = '';
					}
				}
				break;
			case IBusinessName.SHARED_PDF:
				const sharePDFTask = BusinessTaskMap.getTask(clientId);
				if (sharePDFTask && sharePDFTask.cmdId) {
					const resp = await cancelPdfWhiteboard(sharePDFTask.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: sharePDFTask.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: sharePDFTask.username,
							userRole: sharePDFTask.userRole,
							cmdId: sharePDFTask.cmdId
						}
					]);
					if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SHARED_PDF).length === 0) {
						const result = await deletePdfWhiteboard(AgentService.pdfWhiteBoardId);
						AgentService.pdfWhiteBoardId = '';
						setSharePdfBtnStatus('default');
					}
				}
				break;
			case IBusinessName.TRANSCRIPT_OF_TESTIMONY:
				const testimonyWriteTask = BusinessTaskMap.getTask(clientId);
				if (testimonyWriteTask && testimonyWriteTask.cmdId) {
					const resp = await cancelTestimonyWrite(testimonyWriteTask.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: testimonyWriteTask.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: testimonyWriteTask.username,
							userRole: testimonyWriteTask.userRole,
							cmdId: testimonyWriteTask.cmdId
						}
					]);
				}
				break;
			case IBusinessName.SEND_VARIABLE_COLLECTION:
				const collectVariableTask = BusinessTaskMap.getTask(clientId);
				if (collectVariableTask && collectVariableTask.cmdId) {
					const resp = await cancelCollectVariable(collectVariableTask.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: collectVariableTask.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: collectVariableTask.username,
							userRole: collectVariableTask.userRole,
							cmdId: collectVariableTask.cmdId
						}
					]);
				}
				break;
			case IBusinessName.SEND_VIDEO_COLLECTION:
				const videoCollectionTask = BusinessTaskMap.getTask(clientId);
				if (videoCollectionTask && videoCollectionTask.cmdId) {
					const resp = await cancelCollectShortVideo(videoCollectionTask.cmdId.toString(), clientId);
					setBusiness([
						...business,
						{
							name: videoCollectionTask.name,
							clientId: clientId,
							status: IBusinessStatus.CANCEL,
							username: videoCollectionTask.username,
							userRole: videoCollectionTask.userRole,
							cmdId: videoCollectionTask.cmdId
						}
					]);
				}
				break;
			case IBusinessName.REGIONAL_SCREEN_RECORDING:
				console.log('REGIONAL_SCREEN_RECORDING:', clientId, recordRegion());
				await stopRecordRegionalScreen(clientId, recordRegion().publicationId, recordRegion().recordId);
				setRecordRegion({ clientId: '', publicationId: '', recordId: '', recordStatus: IBusinessStatus.DONE });
				if (AgentService.currentAgentStream?.clientId) {
					let key = AgentService.currentAgentStream?.clientId! + '-regionalScreenRecording';
					await BusinessTaskMap.updateTaskStatus(key, IBusinessStatus.DONE, null);
					await BusinessTaskMap.delTask(key);
				}
				break;
			default:
				break;
		}
		const receiver = AgentService.getCustomerMediaStream().find(item => item.clientId === clientId);
		receiver && notifyOtherAgents(businessName, IBusinessStatus.CANCEL, receiver);
	};

	const reveiceBusiness = (data: any) => {
		console.log('reveiceBusiness:', data);
		setBusiness([...business, data?.data || null]);
		if (data && data.data) {
			notifyOtherAgents(data.data.name, data.data.status, data.data);
		}
	};

	useEffect(() => {
		setCustomerMembers([...allMembers().filter(item => item.label === 'customer')]);
		setAgentMembers([...allMembers().filter(item => item.label === 'agent')]);
		console.log('allMembers:', allMembers(), customerMembers(), agentMembers());
	}, [allMembers()]);

	useEffect(() => {
		if (!eventRef.current && AgentService.user?.clientId) {
			onBusinessInit();
			eventRef.current = true;
		}
	}, [AgentService.user?.clientId]);

	const receiveBroadcast = (data: IReceiveBroadcas) => {
		ReceiveBroadcastMap.set(data.data.content.toClientId, data);
		console.log('receiveBroadcast:', ReceiveBroadcastMap, data);
	};

	return (
		<BusinessContext.Provider
			children={children}
			value={{
				customerMembers,
				agentLeaveSession,
				agentMembers,
				business,
				record,
				screenId,
				setScreenId,
				setAllMembers,
				setBusiness,
				membersJoin,
				membersLeave,
				setRecord,
				getCustomerMembers,
				getMembersLabel,
				sendBusiness,
				setAgentName,
				BusinessTaskMap,
				cancelBusiness,
				setCustomerMembers,
				notifyOtherAgents,
				setBizScenarioId,
				bizScenarioId,
				formBusiness,
				startTestiMonyWrite,
				whiteBoardBtnStatus,
				setWhiteBoardBtnStatus,
				sharePdfBtnStatus,
				setSharePdfBtnStatus,
				startWhiteBoard,
				startPdfWhiteBoard,
				recordRegion,
				setRecordRegion
			}}
		></BusinessContext.Provider>
	);
};

const useBusiness = () => {
	const context = React.useContext(BusinessContext);
	if (!context) {
		throw new Error('useBusiness 必须在 AppProvider 中使用');
	}
	return context;
};

export { useBusiness, BusinessProvider };
